//
//  PreViewController.swift
//  SwiftPhtotEdit
//
//  Created by aw031 on 16/10/2025.
//

import UIKit
import SnapKit

//class PreViewController: UIViewController {
//
//    lazy var preImageView: UIImageView = {
//        let imgView = UIImageView()
//        imgView.contentMode = .scaleAspectFit
//        return imgView
//    }()
//
//
//    var preImage : UIImage!
//    override func viewDidLoad() {
//        super.viewDidLoad()
//
//        // Do any additional setup after loading the view.
//
//        view.addSubview(preImageView)
//
//        self.view.backgroundColor = .cyan
//
//       let height = (KScreenWidth - KScreenWValue(32))/self.preImage.size.width * self.preImage.size.height
//        preImageView.image = self.preImage
//        preImageView.snp.makeConstraints { make in
//            make.leading.equalTo(KScreenWValue(16))
//            make.trailing.equalTo(-KScreenWValue(16))
//            make.top.equalToSuperview().offset(KStatusAndNavigationHeight + KScreenWValue(16))
//            make.height.equalTo(height)
//        }
//
////        PhotoTools.saveImage(with: self.imageView.image!) { saveSuccess, error in
////            if saveSuccess {
////                print("保存成功")
////            } else {
////                print("保存失败: \(error?.localizedDescription ?? "未知错误")")
////            }
////        }
//    }
//
//
//    /*
//    // MARK: - Navigation
//
//    // In a storyboard-based application, you will often want to do a little preparation before navigation
//    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//        // Get the new view controller using segue.destination.
//        // Pass the selected object to the new view controller.
//    }
//    */
//
//}


class PreViewController: UIViewController {
    
    
    lazy var bgImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleToFill
        imageView.isUserInteractionEnabled = true
        imageView.clipsToBounds = true
        imageView.backgroundColor = .yellow
        return imageView
    }()
    
    
    
    lazy var preImageView: UIImageView = {
        let imgView = UIImageView(image: self.preImage)
        imgView.contentMode = .scaleAspectFit
        imgView.isUserInteractionEnabled = true
        imgView.backgroundColor = .clear
        return imgView
    }()
    
    var preImage: UIImage!
    
    // 手势相关
    private var currentScale: CGFloat = 1.0
    private var lastScale: CGFloat = 1.0
    private var lastTranslation: CGPoint = .zero
    
    lazy var changeColorBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("修改背景色", for: .normal)
        btn.backgroundColor = .red
        btn.addTarget(self, action: #selector(changeColorBtnUpdataAction), for: .touchUpInside)
        return btn
    }()
    
    
    lazy var selectPhotoBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("选择图片", for: .normal)
        btn.backgroundColor = .cyan
        btn.addTarget(self, action: #selector(clickSelectPhotoAction), for: .touchUpInside)
        return btn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupGestures()
    }
    
    private func setupUI() {
        view.backgroundColor = .white
        
        let width = (KScreenWidth - KScreenWValue(32))
        let height = width/self.preImage.size.width * self.preImage.size.height
        
        view.addSubview(bgImageView)
        bgImageView.addSubview(preImageView)
        
        view.addSubview(selectPhotoBtn)
        view.addSubview(changeColorBtn)
        bgImageView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(KStatusAndNavigationHeight + 16)
            make.leading.equalToSuperview().offset(KScreenWValue(16))
            make.trailing.equalToSuperview().offset(-KScreenWValue(16))
            make.height.equalTo(height)
        }
        
        
        preImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        
        changeColorBtn.snp.makeConstraints { make in
            make.top.equalTo(bgImageView.snp.bottom).offset(16)
            make.leading.equalToSuperview().offset(KScreenWValue(16))
            make.height.equalTo(40)
        }
        
        selectPhotoBtn.snp.makeConstraints { make in
            make.top.bottom.width.equalTo(changeColorBtn)
            make.leading.equalTo(changeColorBtn.snp.trailing).offset(KScreenWValue(16))
            make.trailing.equalToSuperview().offset(-KScreenWValue(16))
        }
        
        
    }
    
    private func setupGestures() {
        // 捏合手势 - 缩放
        let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(_:)))
        preImageView.addGestureRecognizer(pinchGesture)
        
        // 拖拽手势 - 平移
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
        panGesture.minimumNumberOfTouches = 1
        panGesture.maximumNumberOfTouches = 1
        preImageView.addGestureRecognizer(panGesture)
        
        // 双击手势 - 重置
        let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(_:)))
        doubleTapGesture.numberOfTapsRequired = 2
        preImageView.addGestureRecognizer(doubleTapGesture)
    }
    
    @objc private func handlePinch(_ gesture: UIPinchGestureRecognizer) {
        switch gesture.state {
        case .began:
            lastScale = currentScale
            
        case .changed:
            let newScale = lastScale * gesture.scale
            // 限制缩放范围
            currentScale = min(max(newScale, 0.5), 4.0)
            updateTransform()
            
        case .ended, .cancelled:
            lastScale = currentScale
            
        default:
            break
        }
    }
    
    @objc private func handlePan(_ gesture: UIPanGestureRecognizer) {
        let translation = gesture.translation(in: view)
        
        switch gesture.state {
        case .changed:
            // 更新位置，不限制边界
            preImageView.center.x += translation.x
            preImageView.center.y += translation.y
            gesture.setTranslation(.zero, in: view)
            
        default:
            break
        }
    }
    
    @objc private func handleDoubleTap(_ gesture: UITapGestureRecognizer) {
        // 双击重置
        UIView.animate(withDuration: 0.3) {
            self.currentScale = 1.0
            self.lastScale = 1.0
            self.preImageView.transform = .identity
            self.preImageView.center = CGPointMake(self.bgImageView.frame.size.width/2, self.bgImageView.frame.size.height/2)
            //            self.preImageView.snp.remakeConstraints { make in
            //                make.edges.equalToSuperview()
            //            }
        }
    }
    
    private func updateTransform() {
        preImageView.transform = CGAffineTransform(scaleX: currentScale, y: currentScale)
    }
    
    @objc func changeColorBtnUpdataAction(_ sender : UIButton) {
        
        let color = UIColor.randomColor()
        
        bgImageView.backgroundColor = color
        
    }
    
    @objc func clickSelectPhotoAction(_ sender : UIButton) {
        PhotoTools.shared.showPhotoAndCameraPicker(in: self, isPhoto: true, resultHandler:{ [weak self] img in
            self?.bgImageView.image = img
        })
    }
    
}


//class PreViewController: UIViewController {
//
//    lazy var bgImageView: UIImageView = {
//        let imageView = UIImageView()
//        imageView.contentMode = .scaleToFill
//        return imageView
//    }()
//
//    lazy var scrollView: UIScrollView = {
//        let scrView = UIScrollView()
//        scrView.delegate = self
//        scrView.minimumZoomScale = 0.5
//        scrView.maximumZoomScale = 5.0
//        scrView.showsHorizontalScrollIndicator = false
//        scrView.showsVerticalScrollIndicator = false
//        scrView.backgroundColor = .clear
//        scrView.bounces = false         // 禁用弹性效果，避免拖拽时的回弹
//        scrView.bouncesZoom = true      // 允许缩放弹性
//        scrView.alwaysBounceVertical = false    // 禁用垂直弹性
//        scrView.alwaysBounceHorizontal = false  // 禁用水平弹性
//        scrView.contentInsetAdjustmentBehavior = .never  // 避免自动调整contentInset
//        scrView.clipsToBounds = false   // 允许内容超出边界显示
//        return scrView
//    }()
//
//
//
//    //    private var imageView: UIImageView!
//    var preImage : UIImage!
//
//    lazy var preImageView: UIImageView = {
//        let imgView = UIImageView(image: self.preImage)
//        imgView.contentMode = .scaleAspectFit
//        imgView.isUserInteractionEnabled = true
//        imgView.backgroundColor = .clear
//        return imgView
//    }()
//
//    lazy var changeColorBtn: UIButton = {
//        let btn = UIButton(type: .custom)
//        btn.setTitle("修改背景色", for: .normal)
//        btn.backgroundColor = .red
//        btn.addTarget(self, action: #selector(changeColorBtnUpdataAction), for: .touchUpInside)
//        return btn
//    }()
//
//
//    lazy var selectPhotoBtn: UIButton = {
//        let btn = UIButton(type: .custom)
//        btn.setTitle("选择图片", for: .normal)
//        btn.backgroundColor = .cyan
//        btn.addTarget(self, action: #selector(clickSelectPhotoAction), for: .touchUpInside)
//        return btn
//    }()
//
//    private var initialImageSize: CGSize = .zero
//
//
//    override func viewDidLoad() {
//        super.viewDidLoad()
//        self.view.backgroundColor = .white
//        setupUI()
//        setupGestures()
//    }
//
//    private func setupUI() {
//
//        let btn = UIButton(type: .custom)
//        btn.setTitle("<", for: .normal)
//        btn.setTitleColor(.black, for: .normal)
//        btn.addTarget(self, action: #selector(clickUpdataAction), for: .touchUpInside)
//        self.view.addSubview(btn)
//        btn.snp.makeConstraints { make in
//            make.top.equalTo(KStatusBarHeight)
//            make.leading.equalTo(16)
//            make.width.height.equalTo(44)
//        }
//
//        view.addSubview(bgImageView)
//        view.addSubview(scrollView)
//        view.addSubview(changeColorBtn)
//        view.addSubview(selectPhotoBtn)
//
//        scrollView.addSubview(self.preImageView)
//        let width = (KScreenWidth - KScreenWValue(32))
//        let height = width/self.preImage.size.width * self.preImage.size.height
//        initialImageSize = CGSizeMake(width, height)
//
//        bgImageView.snp.makeConstraints { make in
//            make.top.equalToSuperview().offset(KStatusAndNavigationHeight + 16)
//            make.leading.equalToSuperview().offset(KScreenWValue(16))
//            make.trailing.equalToSuperview().offset(-KScreenWValue(16))
//            make.height.equalTo(height)
//        }
//
//        // 确保背景视图允许内容超出边界
//        bgImageView.clipsToBounds = false
//        scrollView.snp.makeConstraints { make in
//            make.edges.equalTo(bgImageView)
//        }
//
//
//        // 设置contentSize，允许图片可以完全拖出父视图
//        // contentSize需要比ScrollView大，这样图片才能完全移出可见区域
//        let scrollViewSize = CGSize(width: width, height: height)
//        let extraSize: CGFloat = 1000 // 额外的空间，确保图片可以完全拖出
//
//        scrollView.contentSize = CGSize(
//            width: scrollViewSize.width + extraSize,
//            height: scrollViewSize.height + extraSize
//        )
//
//        // 设置初始偏移，让图片居中显示
//        let initialOffset = CGPoint(x: extraSize/2, y: extraSize/2)
//        scrollView.setContentOffset(initialOffset, animated: false)
//
//        // 设置图片视图的frame，放在contentSize的中心
//        preImageView.frame = CGRect(
//            x: extraSize/2,
//            y: extraSize/2,
//            width: width,
//            height: height
//        )
//        //        // ImageView 约束
//        //        preImageView.snp.makeConstraints { make in
//        //            make.center.equalToSuperview()
//        //            make.width.equalTo(width)
//        //            make.height.equalTo(height)
//        //        }
//
//        changeColorBtn.snp.makeConstraints { make in
//            make.top.equalTo(scrollView.snp.bottom).offset(16)
//            make.leading.equalToSuperview().offset(KScreenWValue(16))
//            make.height.equalTo(40)
//        }
//
//        selectPhotoBtn.snp.makeConstraints { make in
//            make.top.bottom.width.equalTo(changeColorBtn)
//            make.leading.equalTo(changeColorBtn.snp.trailing).offset(KScreenWValue(16))
//            make.trailing.equalToSuperview().offset(-KScreenWValue(16))
//        }
//
//
//
//    }
//
//
//    private func setupGestures() {
//        // 双击缩放
//        let doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(_:)))
//        doubleTap.numberOfTapsRequired = 2
//        scrollView.addGestureRecognizer(doubleTap)
//
//        // 添加缩放手势识别器
//        let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(handlePinchGesture(_:)))
//        scrollView.addGestureRecognizer(pinchGesture)
//    }
//
//    @objc private func handleDoubleTap(_ gesture: UITapGestureRecognizer) {
//        if scrollView.zoomScale > 1 {
//            // 缩放到最小
//            scrollView.setZoomScale(1, animated: true)
//        } else {
//            // 放大到指定位置
//            let point = gesture.location(in: scrollView)
//            let zoomScale = 2.0
//            let zoomRect = zoomRectForScale(scale: zoomScale, center: point)
//            scrollView.zoom(to: zoomRect, animated: true)
//        }
//    }
//
//    private func zoomRectForScale(scale: CGFloat, center: CGPoint) -> CGRect {
//        var zoomRect = CGRect.zero
//        let scrollViewSize = scrollView.bounds.size
//
//        // 计算缩放后的视图大小
//        zoomRect.size.width = scrollViewSize.width / scale
//        zoomRect.size.height = scrollViewSize.height / scale
//
//        // 计算缩放矩形的原点，使点击位置成为缩放中心
//        zoomRect.origin.x = center.x - (zoomRect.size.width / 2.0)
//        zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0)
//
//        return zoomRect
//    }
//
//    @objc private func handlePinchGesture(_ gesture: UIPinchGestureRecognizer) {
//        if gesture.state == .began {
//            // 记录开始缩放时的状态
//        } else if gesture.state == .changed {
//            // 实时缩放
//            let scale = gesture.scale
//            let newScale = scrollView.zoomScale * scale
//            let clampedScale = max(scrollView.minimumZoomScale, min(scrollView.maximumZoomScale, newScale))
//
//            if clampedScale != scrollView.zoomScale {
//                // 获取缩放中心点
//                let center = gesture.location(in: scrollView)
//                let zoomRect = zoomRectForScale(scale: clampedScale, center: center)
//                scrollView.zoom(to: zoomRect, animated: false)
//            }
//
//            gesture.scale = 1.0
//        }
//    }
//
//
//    @objc func clickUpdataAction(_ sender : UIButton) {
//        navigationController?.popViewController(animated: true)
//    }
//
//
//    @objc func changeColorBtnUpdataAction(_ sender : UIButton) {
//
//        let color = UIColor.randomColor()
//
//        bgImageView.backgroundColor = color
//
//    }
//
//    @objc func clickSelectPhotoAction(_ sender : UIButton) {
//        PhotoTools.shared.showPhotoAndCameraPicker(in: self, isPhoto: true, resultHandler:{ [weak self] img in
//            self?.bgImageView.image = img
//        })
//    }
//
//    private func centerImageView() {
//        // 由于我们使用了更大的contentSize和固定位置的图片，
//        // 这里主要处理缩放后的居中效果
//        let scrollViewSize = scrollView.bounds.size
//        let imageViewSize = preImageView.frame.size
//
//        // 当图片小于ScrollView时，计算居中偏移
//        if imageViewSize.width < scrollViewSize.width && imageViewSize.height < scrollViewSize.height {
//            let horizontalPadding = (scrollViewSize.width - imageViewSize.width) / 2
//            let verticalPadding = (scrollViewSize.height - imageViewSize.height) / 2
//
//            scrollView.contentInset = UIEdgeInsets(
//                top: verticalPadding,
//                left: horizontalPadding,
//                bottom: verticalPadding,
//                right: horizontalPadding
//            )
//        } else {
//            // 图片大于ScrollView时，不需要contentInset
//            scrollView.contentInset = UIEdgeInsets.zero
//        }
//    }
//}

//// MARK: - UIScrollViewDelegate
//extension PreViewController: UIScrollViewDelegate {
//
//    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
//        return preImageView
//    }
//
//    func scrollViewDidZoom(_ scrollView: UIScrollView) {
//        centerImageView()
//    }
//}


